package com.itheima.websocket.config;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Class: HttpRedirectHttps
 * @Package com.itheima.websocket.config
 * @Description: http访问重定向https
 * @Company: http://www.itheima.com/
 */
@Configuration
public class HttpRedirectHttps {

    @Value("${http.port}")
    Integer httpPort;
    @Value("${server.port}")
    Integer httpsPort;


    /*
     * @Description: 配置一个TomcatServletWebServerFactory 的BEAN
     * 然后添加一个Tomcat中的Connector（监听80端口）,并将请求转发到80端口
     * @Method: tomcatServletWebServerFactory
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory
     *
     */

    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(createTomcatConnector());
        return tomcat;

    }


    /*
     * @Description:
     * Spring Boot 不支持同时启动 HTTP 和 HTTPS ，为了解决这个问题，我们这里可以配置一个请求转发，当用户发起 HTTP 调用时，自动转发到 HTTPS 上
     *
     * @Method: createTomcatConnector
     * @Param: []
     * @Update:
     * @since: 1.0.0
     * @Return: org.apache.catalina.connector.Connector
     *
     */
    public Connector createTomcatConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的默认端口号
        connector.setPort(httpPort);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号,也就是项目配置的port
        connector.setRedirectPort(httpsPort);
        return connector;
    }

}
